package org.dromara.common.dynamicDs.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.rpc.RpcContext;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.dynamicDs.annotation.Isolate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author: gxp
 * @desc: todo
 * @create: 2024-09-27 11:04
 **/
public class DsUtil {
    public static String getDataSource(Isolate isolate) {
        String tenantDsName = getContextId(TenantConstants.TENANT_DS_KEY);
        if (StringUtils.isEmpty(tenantDsName)) {
            //没有租户信息，使用默认数据源
            return TenantConstants.DEFAULT_TENANT_DS_NAME;
        }
        return tenantDsName;
    }

    /**
     * 获取当前请求 request
     */
    public static HttpServletRequest getCurrentHttpRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        }

        return null;
    }

    /**
     * 从上下文中获取传递的数据
     *
     * @param key
     * @return
     */
    public static String getContextId(String key) {
        HttpServletRequest request = getCurrentHttpRequest();
        if (request != null) {
            //web请求
            String tenantDsName = request.getHeader(key);
            if (StringUtils.isNotEmpty(tenantDsName)) {
                return tenantDsName;
            }
        } else {
            String tenantDsName = (String)RpcContext.getContext().getObjectAttachment(key);
            if (StringUtils.isNotEmpty(tenantDsName)) {
                return tenantDsName;
            }
        }
        return null;
    }
}
